$(document).ready(function() {
	// $("#roleUserTable").dataTable();
	// 角色名验证
	jQuery.validator.addMethod("isRolename", function(value, element) {
		var rolename = /^[\u0391-\uFFE5\w]+$/;
		return this.optional(element) || (rolename.test(value));
	}, "不能输入特殊字符，请正确输入");

	// 角色中文名验证
	jQuery.validator.addMethod("isChName", function(value, element) {
		var chn = /[^u4e00-u9fa5]/;
		var spe = /^[\u0391-\uFFE5\w]+$/;
		return this.optional(element) || (chn.test(value) && spe.test(value));
	}, "角色中文名以汉字组成");

	// 为addUser注册validate函数
	$("#addRoleForm").validate({
		event : "keyup",
		rules : {
			rolename : {
				required : true,
				// minlength:2,
				// maxlength:20,
				isRolename : true
			},
			name : {
				required : true,
				// minlength:2,
				// maxlength:20,
				isRolename : true
			}

		},
		messages : {
			rolename : {
				required : "请输入角色ID"
			// minlength: "角色名长度至少为 3字符",
			// maxlength: "角色名长度最大为 20 字符"
			},
			name : {
				required : "请输入角色名"
			// minlength: "角色名长度至少为 2字符",
			// maxlength: "角色名长度最大为 20 字符"
			}

		},
		success : function(label) {
			// label指向上面那个错误提示信息标签em
			label.text("") // 清空错误提示消息
			.addClass("success"); // 加上自定义的success类
		}
	});

	// 为addUser注册validate函数
	$("#editRoleForm").validate({
		event : "keyup",
		rules : {
			rolename : {
				required : true,
				isRolename : true
			},
			name : {
				required : true,
				isChName : true
			}

		},
		messages : {
			rolename : {
				required : "请输入角色ID"
			},
			name : {
				required : "请输入角色名"
			}

		},
		success : function(label) {
			// label指向上面那个错误提示信息标签em
			label.text("") // 清空错误提示消息
			.addClass("success"); // 加上自定义的success类
		}
	});

	disableAppRolePrivilege();

	disableAppRolePrivilegeDeletabele();

});

/**
 * 区分应用角色和用户组角色(应用角色不能授权)
 */
function disableAppRolePrivilege() {
	var roleTypes = $(".roleTypeInput");
	for ( var i = 0; i < roleTypes.length; i++) {
		var roleInput = $(roleTypes[i]);
		var type = roleInput.val();

		var privilegeBtn = roleInput.parent().find(".privilege-btn");
		var editBtn = roleInput.parent().find(".edit-btn");
		if (type != "1") {
			editBtn.attr("disabled", "");
			editBtn.click(function() {
				return false;
			});
			privilegeBtn.attr("disabled", "");
			privilegeBtn.click(function() {
				return false;
			});
		} else {
			privilegeBtn.click(function() {
				var roleid = $(this).data("roleid");
				privilegeModal(roleid);
			})
		}
	}
}

/**
 * 区分应用角色和用户组角色(应用角色不能被删除)
 */
function disableAppRolePrivilegeDeletabele() {
	$("#roleListBody td[roleType='0']").each(function(index) {
		$("#roleListBody td[roleType='0']")[index].children[0].remove();
	});
}

/*
 * 增加角色接口方法
 */
function addRole() {
	var rolename = $("#input-rolename").val();
	var chinesename = $("#input-chinesename").val();
	var roleType = $("#roleType").val();
	var url = "addRole";
	var form = $("#addRoleForm");
	submitToUrl(form, url, rolename, chinesename, roleType, "添加成功！");
}

/*
 * 编辑角色接口方法
 */
function editRole(roleId, rName, rChnName) {
	// rName和rChnName为修改前的数据，用于对比输入框有没有进行修改操作
	var rolename = $("#edit-input-rolename").val();
	var chinesename = $("#edit-input-chinesename").val();

	if (rName == rolename && rChnName == chinesename) {
		// 用户什么都没改，点保存直接关闭窗口
		$("#editRoleModal").modal('hide');
		return;
	}

	var roleType = $("#edit-roleType").val();
	var url = "updateRole";
	var form = $("#editRoleForm");
	var roleId = $("#edit-roleId").val();
	submitToUrl(form, url, rolename, chinesename, roleType, "编辑成功！", roleId);
}

function showEditWindow(rolename, name, roleType, roleId) {

	$("#edit-input-rolename").val(rolename);
	$("#edit-input-chinesename").val(name);
	roleType = parseInt(roleType);
	$("#edit-roleType").val(roleType);
	$("#edit-roleId").val(roleId);

	$("#btn-editRole").unbind('click');
	$("#btn-editRole").on('click', function() {
		editRole(roleId, rolename, name)
	});
}

function submitToUrl(form, url, rolename, chinesename, roleType, msg, roleId) {

	roleType = parseInt(roleType);

	var data = [ {
		name : 'rolename',
		value : rolename
	}, {
		name : 'name',
		value : chinesename
	}, {
		name : 'roleType',
		value : roleType
	} ];
	if (roleId) {
		data.push({
			name : "id",
			value : roleId
		});
	}

	var isSubmit = form.valid();

	if (isSubmit) {
		$.ajax({
			url : url,
			type : 'post',
			data : data,
			dataType : "json",
			success : function(response) {
				if (response.result == "success") {
					bootbox.alert(msg, function() {
						window.location.reload();
					});

				} else {
					bootbox.alert(response.message);
				}
			},
			error : function() {
				bootbox.alert("服务器繁忙，请稍后再试！");
			}
		});
	}
}

function getIDs(div_id) {
	var checkIds = [];
	$("#" + div_id + " input[type='checkbox']").each(function(index) {
		if ($(this).is(':checked')) {
			var id = $(this).val();
			checkIds.push(id);
		}
	});
	return checkIds;
}

function deleteRoles() {
	var ids = getIDs("roleListBody");
	if (ids.length == 0) {
		bootbox.alert("请至少选择一项");
		return;
	}
	bootbox.confirm("是否要删除角色？", function(result) {
		if (result) {

			var data = [ {
				name : 'ids',
				value : ids
			} ];

			// 检查依赖关系，与用户存在依赖关系，则不允许删除角色
			$.ajax({
				url : "checkRolesDepends",
				type : 'post',
				data : data,
				success : function(response) {

					console.log(response.roleName);
					if (response.roleName.length != 0) {
						var msg = "";
						for (i in response.roleName) {
							msg = msg + '"' + response.roleName[i] + '" ';
						}
						bootbox.alert("角色: " + msg
								+ " 与用户存在依赖关系，请解除依赖关系再进行删除操作");
					} else {
						// 删除角色请求
						$.ajax({
							url : "deleteRoles",
							type : 'post',
							data : data,
							success : function(response) {
								if (response.result == "success") {

									var reload = function() {
										var url = window.location.href;

										if (url.indexOf("page=") > 0) {
											url = url.replace("page=",
													"old_pa=");
											url += "&page=1";
											window.location.href = url;
										} else {
											window.location.reload();
										}
									};

									bootbox.alert("删除成功！", reload);

								} else {
									bootbox.alert("删除失败！");
								}
							},
							error : function() {
								bootbox.alert("服务器繁忙，请稍后再试！");
							}
						});
					}

				},
				error : function() {
					bootbox.alert("服务器繁忙，请稍后再试！");
				}
			});

		} else {
			return;
		}

	});

}

/*
 * 批量保存权限信息
 */
function savePrivileges(roleID) {
	var privilegeList = [];
	var appId = $('#appSelecterAppId').val();
	var operation = $('#content_table tr');
	$(operation).each(
			function(index) {
				var tdObject = $(this).children("td:eq(1)");
				var module_ID = $(tdObject).attr("id");// 模块id
				var opIDs = [];// 操作权限集合
				var checkboxOperation = $(tdObject).find(
						"input[type='checkbox']:checked");// 获取操作项checkbox对象集合
				checkboxOperation.each(function(index) {
					var id = $(this).val();
					opIDs.push(id);
				});
				// 组装操作权限对象
				if (opIDs.length != 0) {
					var privilege = new Object();
					privilege.role_ID = roleID;
					privilege.app_ID = appId;
					privilege.module_ID = module_ID;
					privilege.operation_IDs = opIDs;
					privilegeList.push(privilege);
				}
			});
	// 调用保存接口
	if (privilegeList.length != 0) {
		var json = JSON.stringify(privilegeList);
		var data = [ {
			name : 'privilegeList',
			value : json
		} ];
		$.ajax({
			url : "savePrivileges",
			type : 'post',
			data : data,
			dataType : 'json',
			success : function(response) {
				if (response.result == "success") {
					bootbox.alert("保存成功！", function() {
						window.location.reload();
					});
				} else {
					bootbox.alert("保存失败！")
				}
			},
			error : function() {
				bootbox.alert("服务器繁忙，请稍后再试！");
			}
		});
	}
}

function privilegeModal(roleID) {
	var loadurl = 'showPrivileges?roleID=' + roleID;
	$.get(loadurl, function(data) {
		bootbox.dialog({
			message : data,
			title : "授权管理",
			buttons : {
				danger : {
					label : "关闭",
					className : "btn btn-common btn-small tls"
				},
				success : {
					label : "确定",
					className : "btn btn-primary btn-small tls",
					callback : function() {
						savePrivileges(roleID);
						return false;
					}
				}
			}
		});
	});
}

// 在角色页面上点击"用户设置"
function showRoleUserList(roleID) {

	var div_role_user = $('#div-role-user');
	var btn_addUser = $("#btn-addUser");
	var btn_deleteUser = $("#btn-deleteUser");

	btn_addUser.unbind('click');
	btn_deleteUser.unbind('click');

	var data = [ {
		name : 'roleID',
		value : roleID
	} ];

	$
			.ajax({
				url : "getUsersByRoleID",
				type : 'post',
				data : data,
				success : function(result) {

					btn_addUser.on('click', function() {
						addRoleUser(roleID)
					});
					btn_deleteUser.on('click', function() {
						deleteRoleUser(roleID);
					});
					// console.log(result.userList);

					var users = result.userList;
					div_role_user.show();
					window.location.href = "#userInfo";
					// createUserListTemplate(users);

					var tbody = $("#tbody-userList");
					tbody.html('');
					// console.log(users);
					for (i in users) {
						// table.append(users[i].username);
						var userType = '';
						if (users[i].userCategoryVO != null) {
							userType = users[i].userCategoryVO.name;
						}
						tbody
								.append('<tr style="background-color: rgb(255, 255, 255);" class="RoleUserTd" id="'
										+ users[i].id
										+ '">'
										+ '<td class="bd_txt3" >'
										+ '<input class="choice-w" type="checkbox" '
										+ 'name="checkbox"  value="'
										+ users[i].id
										+ '">'
										+ '</td>'
										+ '<td class="bd_txt3">'
										+ users[i].username
										+ '</td>'
										+ '<td class="bd_txt3">'
										+ users[i].name
										+ '</td>'
										// + '<td class="bd_txt3">' + userType
										// +'</td>'
										+ '<td class="bd_txt3">'
										+ users[i].lockStatus
										+ '</td>'
										+ '</tr>');
					}

					// $('#roleUserTable').dataTable({
					// "bPaginate": true,
					// "bLengthChange": false,
					// "bFilter": false,
					// "bSort": false,
					// "bInfo": true,
					// "bAutoWidth": false

					// });

				},
				error : function() {
					bootbox.alert("服务器繁忙，请稍后再试！");
				}
			});
}

// 增加角色中的用户
function addRoleUser(roleID) {
	var tbody = $("#tbody-modal-userList");
	var btn_save = $("#btn-addRoleUser");
	btn_save.unbind('click');
	tbody.html('');
	var data = [ {
		name : 'roleID',
		value : roleID
	} ];
	$
			.ajax({
				url : "getMoreRoleUser",
				type : 'post',
				data : data,
				success : function(result) {
					// console.log(result);
					btn_save.on('click', function() {
						saveRoleUser(roleID)
					});
					for (i in result) {
						tbody
								.append('<tr style="background-color: rgb(255, 255, 255);">'
										+ '<td class="bd_txt3">'
										+ '<input class="choice-w" type="checkbox" name="cb" value="'
										+ result[i].id
										+ '"></td>'
										+ '<td class="bd_txt3 bd_le">'
										+ result[i].username
										+ '</td>'
										+ '<td class="bd_txt3 bd_le">'
										+ result[i].name + '</td>' + '</tr>');
					}
					$('#addRoleUserModal').modal("show");

				},
				error : function() {
					bootbox.alert("服务器繁忙，请稍后再试！");
				}
			});

}

// 保存角色中的新增用户的结果
function saveRoleUser(roleID) {

	var usersID = getIDs("tbody-modal-userList");
	if (usersID.length == 0) {
		bootbox.alert("请至少选择一项");
		return;
	}
	var data = [ {
		name : 'roleID',
		value : roleID
	}, {
		name : 'usersID',
		value : usersID
	} ];

	$.ajax({
		url : "saveRoleUser",
		type : 'post',
		data : data,
		success : function(result) {

			if (result.result == "success") {

				bootbox.alert("保存成功！", function() {
					$('#addRoleUserModal').modal('hide');
					// window.location.reload();
					showRoleUserList(roleID);
				});

			} else {
				bootbox.alert("保存失败！")
			}

		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});
}

// 删除角色中的用户
function deleteRoleUser(roleID) {
	var userIDs = getIDs("tbody-userList");
	if (userIDs.length == 0) {
		bootbox.alert("请至少选择一项");
		return;
	}
	bootbox.confirm("是否要删除角色中关联的用户？", function(result) {

		if (result) {

			var data = [ {
				name : 'roleID',
				value : roleID
			}, {
				name : 'userIDs',
				value : userIDs
			} ];
			$.ajax({
				url : "deleteRoleUsers",
				type : 'post',
				data : data,
				success : function(result) {
					// console.log(result);
					if (result.result == "success") {
						bootbox.alert("删除成功！", function() {
							// window.location.reload();
							// for( i in userIDs){
							// $("#tbody-userList tr[id='"+ userIDs[i]
							// +"']").remove();
							// }
							showRoleUserList(roleID);
						});

					} else {
						bootbox.alert("删除失败！")
					}

				},
				error : function() {
					bootbox.alert("服务器繁忙，请稍后再试！");
				}
			});
		} else {
			return;
		}
	});

}

function selectAll(id, parent) {
	var selectAllCheckbox = $("#" + id);
	var checkList = $("#" + parent + " input[type='checkbox']");
	if (selectAllCheckbox.is(':checked')) {
		checkList.each(function(index) {
			this.checked = true;
		});
	} else {
		checkList.each(function(index) {
			this.checked = false;
		});
	}
}

var spinner;
function spinit(id) {
	// var target = document.getElementById(id);
	// var spinner = new Spinner(opts).spin(target);
	spinner = new Spinner().spin();
	$("#" + id).append(spinner.el);
	$(spinner.el).css({
		"margin-left" : "225px",
		"margin-top" : "180px"
	});
}

function stopSpining() {
	spinner.stop();
}
